#include "PythonInterpreter.h"

#include <iostream>
#include <filesystem>

#include "MainWindow.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QLabel>

namespace fs = std::filesystem;

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    setWindowTitle("Main Window");
    setGeometry(100, 100, 800, 600);

    QWidget* centralWidget = new QWidget(this);
    this->setCentralWidget(centralWidget);
    centralWidget->setLayout(new QVBoxLayout);
    centralWidget->layout()->setContentsMargins(0, 0, 0, 0);

    auto btn = new QPushButton("Call Python");
    auto label = new QLabel;
    centralWidget->layout()->addWidget(btn);
    centralWidget->layout()->addWidget(label);

    fs::path script_path = fs::current_path() / "python";
    std::cout << "script_path: " << script_path.string() << std::endl;
    PYTHON_INTERPRETER.add_search_path(script_path);
    PYTHON_INTERPRETER.load_module("plot_cross_section"); // 提前加载模块

    connect(btn, &QPushButton::clicked, this, [=]() {
        std::cout << "Button clicked!" << std::endl;

        std::vector<std::string> files = {
        R"(D:\data\fio\chanpin\res\DH\20250205\DH_2025020512_UVEL.NC)",
        R"(D:\data\fio\chanpin\res\DH\20250205\DH_2025020512_VVEL.NC)"
        };
        std::vector<std::string> vars = { "uvel", "vvel" };
        std::pair<double, double> point1 = { 120.0, 30.0 };
        std::pair<double, double> point2 = { 125.0, 32.0 };

        py::object ret = PYTHON_INTERPRETER.call_function("plot_cross_section", "plot_cross_section",
            py::cast(files),
            py::cast(vars),
            py::str("lon"), py::str("lat"), py::str("lay"), py::str("time"),
            py::make_tuple(point1.first, point1.second),
            py::make_tuple(point2.first, point2.second),
            py::int_(0),
            py::float_(0.0), py::float_(100.0), py::int_(10), py::float_(1.0), py::bool_(true)
        );
        if (ret.is_none()) {
            std::cerr << "Python function returned None" << std::endl;
            return;
        }
        std::string filename = ret.cast<std::string>();
        std::cout << "filename: " << filename << std::endl;
        QPixmap pixmap(filename.c_str());
        if (pixmap.isNull()) {
            std::cerr << "Failed to load pixmap: " << filename << std::endl;
            return;
        }
        label->setPixmap(pixmap);
    });
}

MainWindow::~MainWindow()
{

}